const Promise = require('./promise');
const MD5 = require('../utils/md5');
const Util = require('../utils/util');
/*
 * 执行http请求
 *
 * 自动转化配置文件config中的参数转化为url参数
 * 自动补齐header.authrozie
 * 自动补齐header.myclient
 * @param {Object} options 执行wx.request的参数，options.loading是否显示loading.
 * @returns Promise.
 */

class Http {
  static request(options) {
    return new Promise(function (resolve, reject) {
      if(options.loading) {
        wx.showNavigationBarLoading();
      }
      //调试数据暂时写死
      //options.data.openid = 1;
      const config = {
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        url: options.url,
        method: options.method,
        dataType: 'json',
        success: function (res) {
          // console.info(res);
          if(res.statusCode != 200) {
            var interfaceIndex = options.url.lastIndexOf("\/");
            var interfaceName = options.url.substring(interfaceIndex + 1,options.url.length);
            wx.showToast({
              title: `${interfaceName}接口${res.statusCode}错误`,
              icon:'none'
            });
            // reject({
            //   error : true,
            //   message: `接口${res.statusCode}错误`
            // });
          } else {
            resolve(res.data);  
          }
        },
        fail: function (error) {
          // reject({
          //   error: true,
          //   message: '网络异常'
          // });
          wx.showToast({
            title: `网络异常`,
            icon:'none'
          });
        },
        complete: function () {
          if(options.loading) {
            wx.hideNavigationBarLoading();
          }
        }
      };
      var isSign = true;
      if(isSign) {
        var user = wx.getStorageSync('user');
        // if(options.data.openid == 'odp8b5LSegd6PvCeAnTaSy4sgDAg') {
        //   user.key = '';
        // }
        options.data.curtime = Date.parse(new Date());
        options.data.noncestr = Util.randomString(12);
        //如果该用户是店员且该接口需要获取店员自己信息
        if(user.keeper_uid && options.clerkAPI) {
          options.data.openid = user.clerk_openid;
        }
        var searchs = Util.toQueryString(options.data);
        if(user && typeof user.key === 'undefined') {
          user.key = '';
        }
        var querys = searchs + '&key=' + user.key;
        //如果该用户是店员且该接口需要获取店员自己信息
        if(user.keeper_uid && options.clerkAPI) {
          querys = searchs + '&key=' + user.clerk_key;
        }
        options.data.sign = MD5.md5(querys).toUpperCase();
        config.data = options.data;
      } else {
         if(!!options.data) {
          config.data = options.data;
         }
      }
      wx.request(config);
    });
  }
}

module.exports = Http;
